<script setup>
import Phaser from 'phaser';
import { ref, toRaw } from 'vue';
import PhaserGame from '@/views/game/game01/PhaserGame.vue';

const canMoveSprite = ref();
const phaserRef = ref();
const spritePosition = ref({ x: 0, y: 0 });
/**
 * 切换场景事件，在场景创建是触发【current-scene-ready】事件，
 * 然后在PhaserGame.vue中监听【current-scene-ready】事件，
 * 然后在PhaserGame.vue中转换成vue组件事件【current-active-scene】
 * 然后在index.vue中监听【current-active-scene】事件，并触发这个方法
 */
const changeScene = () => {

  const scene = toRaw(phaserRef.value.scene);

  if (scene)
  {
      //  Call the changeScene method defined in the `MainMenu`, `Game` and `GameOver` Scenes
      scene.changeScene();
  }

}
// 移动Sprite
function moveSprite(){

  const scene = toRaw(phaserRef.value.scene);

    if (scene)
    {
        //  Call the `moveLogo` method in the `MainMenu` Scene and capture the sprite position
        scene.moveLogo(({ x, y }) => {

            spritePosition.value = { x, y };

        });
    }
}

// 添加Sprite
const addSprite = () => {
  // toRaw 作用是从一个响应式对象或者代理对象中返回其原始的、非响应式的对象。
  const scene = toRaw(phaserRef.value.scene);

  if (scene)
  {
      //  Add a new sprite to the current scene at a random position
      const x = Phaser.Math.Between(64, scene.scale.width - 64);
      const y = Phaser.Math.Between(64, scene.scale.height - 64);

      //  `add.sprite` is a Phaser GameObjectFactory method and it returns a Sprite Game Object instance
      const star = scene.add.sprite(x, y, 'star');

      //  ... which you can then act upon. Here we create a Phaser Tween to fade the star sprite in and out.
      //  You could, of course, do this from within the Phaser Scene code, but this is just an example
      //  showing that Phaser objects and systems can be acted upon from outside of Phaser itself.
      scene.add.tween({
          targets: star,
          duration: 500 + Math.random() * 1000,
          alpha: 0,
          yoyo: true,
          repeat: -1
      });
  }

}


const currentScene = (scene) => {
    // 只有在MailMenu场景中才能移动Sprite
    canMoveSprite.value = (scene.scene.key !== 'MainMenu');

}


</script>
<template>
  <PhaserGame ref="phaserRef" @current-active-scene="currentScene" />
  <div>
      <div>
          <button class="button" @click="changeScene">Change Scene</button>
      </div>
      <div>
          <button :disabled="canMoveSprite" class="button" @click="moveSprite">Toggle Movement</button>
      </div>
      <div class="spritePosition">Sprite Position:
          <pre>{{ spritePosition }}</pre>
      </div>
      <div>
          <button class="button" @click="addSprite">Add New Sprite</button>
      </div>
  </div>
</template>
